<!-- 商品发布 - 库存价格 -->
<template>
  <el-form ref="formRef" :disabled="isDetail" :model="formData" :rules="rules" label-width="120px">
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>分销设置 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="分销开关" props="subCommissionEnable">
      <el-switch
        v-model="formData.subCommissionEnable"
        @change="changeSubCommissionEnable"
      ></el-switch>
    </el-form-item>
    <el-form-item label="分销类型" props="subCommissionType" v-if="formData.subCommissionEnable">
      <el-radio-group
        v-model="formData.subCommissionType"
        class="w-80"
        @change="changeSubCommissionType"
      >
        <el-radio :value="false">默认设置</el-radio>
        <el-radio :value="true" class="radio">单独设置</el-radio>
      </el-radio-group>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>销量设置</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品在线下渠道有销售，可以填写该商品在线下渠道的销售数据。线上展示销量数据为线下销量+线上销量之和。
      </span>
    </div>
    <el-form-item label="线下销量" prop="virtualSalesCount">
      <el-input-number
        v-model="formData.virtualSalesCount"
        @change="virtualSalesCountChange"
        :min="0"
        placeholder="请输入线下销量"
        class="w-80!"
      />
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>商品规格 </span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px">
        如商品仅有一个规格请使用单规格；如有容量、颜色等多种规格，请使用多规格。
      </span>
    </div>
    <el-form-item label="规格类型" props="specType">
      <el-radio-group v-model="formData.specType" class="w-80" @change="onChangeSpec">
        <el-radio :value="false" class="radio">单规格</el-radio>
        <el-radio :value="true">多规格</el-radio>
      </el-radio-group>
    </el-form-item>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
    >
      <span>规格属性</span>
      <Icon class="ml-5px" :icon="'ep:question-filled'" />
      <span class="ml-5px"> 不同规格商品的图片、零售价、成本价等不同的参数的设置 </span>
    </div>
    <!-- 多规格添加-->
    <el-form-item v-if="!formData.specType">
      <SkuList
        ref="skuListRef"
        :prop-form-data="formData"
        :property-list="propertyList"
        :rule-config="ruleConfig"
      />
    </el-form-item>
    <el-form-item v-if="formData.specType" label="商品规格">
      <ProductAttributes
        :is-detail="isDetail"
        :prop-form-data="formData"
        :property-list="propertyList"
        @success="generateSkus"
      />
      <el-button class="mb-10px mr-15px" @click="handleAttributesAdd">添新加规格</el-button>
    </el-form-item>
    <template v-if="formData.specType">
      <el-form-item v-if="!isDetail" label="批量设置">
        <SkuList :is-batch="true" :prop-form-data="formData" :property-list="propertyList" />
      </el-form-item>
      <el-form-item label="规格列表">
        <SkuList
          ref="skuListRef"
          :is-detail="isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
    </template>
    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
      v-if="!formData.specType || (formData.specType && propertyList.length > 0)"
    >
      <span>关联商品</span>
    </div>
    <el-form-item v-if="!formData.specType">
      <!-- <el-button @click="handleGiveGoods(item)">选择商品</el-button> -->
      <section v-for="(item, index) in formData!.skus" :key="index">
        <el-form-item>
          <el-button @click="handleGiveGoods(item)">选择商品</el-button>
          <SkuListGive
            class="mt-20px"
            ref="SkuListGiveRef"
            v-if="item.spuData?.skus.length > 0"
            :isComponent="false"
            :isDetail="false"
            :hide-stock="true"
            :hide-usable-times="false"
            :prop-form-data="item.spuData"
          >
            <template #extension>
              <el-table-column align="center" label="单次服务用量" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.productConfig.singleUsage"
                    :controls="false"
                    :precision="0"
                  >
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" label="是否参与销售" min-width="100">
                <template #default="{ row }">
                  <el-switch v-model="row.productConfig.inSales" />
                </template>
              </el-table-column>
            </template>
          </SkuListGive>
        </el-form-item>
      </section>
    </el-form-item>
    <template v-if="formData.specType && propertyList.length > 0">
      <section v-for="(item, index) in formData!.skus" :key="index">
        <el-form-item
          v-if="item?.properties && item?.properties?.length > 0"
          :label="`${item.properties[0].propertyName}-${item.properties[0].valueName}`"
        >
          <el-button @click="handleGiveGoods(item)">选择商品</el-button>
          <SkuListGive
            class="mt-20px"
            ref="SkuListGiveRef"
            v-if="item.spuData?.skus.length > 0"
            :isComponent="false"
            :isDetail="false"
            :hide-stock="true"
            :hide-usable-times="false"
            :prop-form-data="item.spuData"
          >
            <template #extension>
              <el-table-column align="center" label="单次服务用量" min-width="168">
                <template #default="{ row }">
                  <el-input-number
                    v-model="row.productConfig.singleUsage"
                    :controls="false"
                    :precision="0"
                  >
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column align="center" label="是否参与销售" min-width="100">
                <template #default="{ row }">
                  <el-switch v-model="row.productConfig.inSales" />
                </template>
              </el-table-column>
            </template>
          </SkuListGive>
        </el-form-item>
      </section>
    </template>

    <div
      class="p-10px border-rd-5px mb-20px border-1px flex flex-items-center bg-[var(--el-color-primary-light-9)] font-size-14px"
      v-if="!formData.specType || (formData.specType && propertyList.length > 0)"
    >
      <span>其他设置</span>
    </div>
    <el-form-item v-if="!formData.specType">
      <SkuListOther
        ref="skuListOtherRef"
        :is-detail="isDetail"
        :prop-form-data="formData"
        :property-list="propertyList"
        :rule-config="ruleConfig"
      />
    </el-form-item>
    <template v-if="formData.specType && propertyList.length > 0">
      <!-- <el-form-item v-if="!isDetail" label="批量设置">
        <SkuListOther :is-batch="true" :prop-form-data="formData" :property-list="propertyList" />
      </el-form-item> -->
      <el-form-item label="规格列表">
        <SkuListOther
          ref="skuListOtherRef"
          :is-detail="isDetail"
          :prop-form-data="formData"
          :property-list="propertyList"
          :rule-config="ruleConfig"
        />
      </el-form-item>
    </template>
  </el-form>
  <!-- 商品属性添加 Form 表单 -->
  <ProductPropertyAddForm ref="attributesAddFormRef" :propertyList="propertyList" />
  <GiveGoodsSelect ref="giveGoodsSelectRef" :isSelectSku="true" @confirm="selectSku" />
</template>
<script lang="ts" setup>
import { PropType } from 'vue'
import { copyValueToTarget, generateNumericUUID, generateSortNumericUUID } from '@/utils'
import { propTypes } from '@/utils/propTypes'
import {
  getPropertyList,
  PropertyAndValues,
  RuleConfig,
  fromDataRule
} from '@/views/mall/product/spu/components/index'
import ProductAttributes from '@/views/mall/product/spu/form/ProductAttributes.vue'
import ProductPropertyAddForm from '@/views/mall/product/spu/form/ProductPropertyAddForm.vue'
import SkuList from './../components/SkuList.vue'
import SkuListOther from './../components/SkuListOther.vue'
import SkuListGive from '@/views/mall/product/components/SkuList.vue'
import GiveGoodsSelect from '@/views/mall/product/components/GiveGoodsSelect.vue'
import * as ProductSpuApi from '@/api/shop/product/spu'

import type { Spu } from '@/api/mall/product/spu'
defineOptions({ name: 'ProductSpuCardSkuForm' })

// sku 相关属性校验规则
const ruleConfig: RuleConfig[] = [
  {
    name: 'skuType',
    rule: (arg) => {
      return arg != undefined
    },
    message: '请选择卡项属性'
  },
  // {
  //   name: 'price',
  //   rule: (arg) => arg >= 0.0,
  //   message: '商品销售价格必须大于等于 0.00 元！！！'
  // },
  // {
  //   name: 'marketPrice',
  //   rule: (arg) => {
  //     if (formData?.salesChannel?.includes(2)) {
  //       return arg >= 0.01
  //     } else {
  //       return true
  //     }
  //   },
  //   message: '商品划线价格必须大于等于 0.01 元！！！'
  // },
  // {
  //   name: 'costPrice',
  //   rule: (arg) => arg >= 0.0,
  //   message: '商品成本价格必须大于等于 0.00 元！！！'
  // },
  // {
  //   name: 'usableDuration',
  //   rule: (arg) => arg != undefined,
  //   message: '可用时长必填！！！'
  // },
  {
    name: 'servicesDuration',
    rule: (arg) => arg != undefined,
    message: '服务时长必填！！！'
  }
]
// ================= 商品选择相关 =================
export interface GiveProductVO {
  spuId: number
  skuId: number
  singleUsage?: number
  inSales?: boolean
}
const giveGoodsSelectRef = ref() // 商品和属性选择 Ref

const nowItem = ref() //当前选中的数据
const handleGiveGoods = (item: any) => {
  nowItem.value = item
  const selectedSkuIds = item.spuData.skus.map((ele) => {
    return ele.skuId
  })
  giveGoodsSelectRef.value.open(selectedSkuIds)
}
const selectSku = (skuIds: number[]) => {
  getSkuDetails(skuIds, undefined, nowItem.value)
}
const getSkuDetails = async (
  skuIds: number[] | undefined,
  products?: GiveProductVO[],
  nowItem?: any
) => {
  const data = await ProductSpuApi.getSkuPageList2({ skuIds } as any)
  if (data.list.length == 0) {
    return
  }
  console.log(nowItem)
  data.list.forEach((sku) => {
    let config: GiveProductVO = {
      skuId: sku.skuId!,
      spuId: sku.spuId!,
      singleUsage: 1,
      inSales: false
    }

    const existData = nowItem.spuData.skus.find((ele: any) => {
      return ele.skuId == sku.skuId
    })
    if (existData) {
      config = existData.productConfig
    }

    if (typeof products !== 'undefined') {
      const product = products.find((item) => item.skuId === sku.skuId)

      config = product || config
    }
    sku.productConfig = config
  })
  if (nowItem) {
    nowItem.spuData = {
      skus: []
    }
    nowItem.spuData.skus = data.list
  }
}

const props = defineProps({
  propFormData: {
    type: Object as PropType<Spu>,
    default: () => {}
  },
  isDetail: propTypes.bool.def(false), // 是否作为详情组件
  activeName: propTypes.string.def('sku')
})
const attributesAddFormRef = ref() // 添加商品属性表单
const formRef = ref() // 表单 Ref
const propertyList = ref<PropertyAndValues[]>([]) // 商品属性列表
const skuListRef = ref() // 商品属性列表 Ref
const formData = reactive<Spu>({
  specType: false, // 商品规格
  spuType: 2, //商品类型
  skus: [],
  salesChannel: [], //销售渠道
  spuId: undefined,
  subCommissionType: false, // 分销类型
  subCommissionEnable: false, //分销开关
  virtualSalesCount: 0
})
/**虚拟销量 */
const virtualSalesCountChange = () => {
  Object.assign(props.propFormData, formData)
}
/** 分销类型 */
const changeSubCommissionEnable = () => {
  formData.subCommissionType = false
  Object.assign(props.propFormData, formData)
}
const changeSubCommissionType = () => {
  // 默认为零，类型切换后也要重置为零
  for (const item of formData.skus!) {
    item.firstBrokeragePrice = 0
    item.secondBrokeragePrice = 0
  }
  Object.assign(props.propFormData, formData)
}
const rules = reactive({
  specType: [required]
})
const handleAttributesAdd = () => {
  let data = {
    id: generateSortNumericUUID(),
    name: '',
    values: []
  }
  propertyList.value.push(data)
}
onMounted(() => {})
/** 将传进来的值赋值给 formData */
watch(
  () => props.propFormData,
  (data) => {
    if (!data) {
      return
    }
    copyValueToTarget(formData, data)
    // 将 SKU 的属性，整理成 PropertyAndValues 数组
    propertyList.value = getPropertyList(data)
  },
  {
    deep: true,
    immediate: true
  }
)

/** 表单校验 */
import { cloneDeep } from 'lodash-es'
/**
 * 获取所有 sku 活动配置
 *
 * @param extendedAttribute 在 sku 上扩展的属性，例：秒杀活动 sku 扩展属性 productConfig 请参考 seckillActivity.ts
 */
const SkuListGiveRef = ref()
const getSkuConfigs = (extendedAttribute: string, item: any) => {
  // SkuListGiveRef.value[0].validateSku()
  const products: any[] = []
  item.spuData.skus?.forEach((sku: any) => {
    products.push(sku[extendedAttribute] as any)
  })
  return products
}
const emit = defineEmits(['update:activeName'])
const message = useMessage() // 消息弹窗

const validate = async () => {
  if (!formRef) return
  try {
    // 校验 sku
    skuListRef.value?.validateSku()
    await unref(formRef).validate()
    formData.skus!.forEach((element: any) => {
      const products = cloneDeep(getSkuConfigs('productConfig', element))

      element.generalProductList = products
      // if (element.generalProductList.length == 0) {
      //   message.error('【关联商品】不完善，请填写相关信息')
      //   emit('update:activeName', 'sku')

      //   return
      // }
    })
    // 校验通过更新数据
    Object.assign(props.propFormData, formData)
  } catch (e) {
    // message.error('【库存价格】不完善，请填写相关信息')
    emit('update:activeName', 'sku')
    throw e // 目的截断之后的校验
  }
}
defineExpose({ validate })

/** 选择规格 */
const onChangeSpec = () => {
  // 重置商品属性列表
  propertyList.value = []
  // 重置sku列表
  formData.skus = [
    {
      picUrl: '', // 图片地址
      skuType: undefined, //商品属性
      price: 0, // 零售价
      marketPrice: 0, // 划线价
      costPrice: 0, // 成本价
      lowPrice: 0, //最低价
      usableTimes: undefined, //可用次数
      usableDuration: undefined, //可用时长
      usableDurationUnit: 1, //时长单位
      servicesDuration: undefined, //服务时长
      firstBrokeragePrice: 0, // 一级分销的佣金
      secondBrokeragePrice: 0, // 二级分销的佣金
      firstBrokeragePercent: 0, // 一级分销的佣金 比例
      secondBrokeragePercent: 0, // 二级分销的佣金 比例
      firstBrokerageType: 2, // 一级分销的佣金类型
      secondBrokerageType: 2, // 二级分销的佣金类型
      servicesFee: 0, //手工费
      isServices: false, //是否计算手工量
      isDebtServices: false, //欠款销售
      isGive: false, //支持赠送
      debtServicesType: undefined, //是否支持欠款服务
      performanceType: 1, //卡项消耗业绩计算方式-左侧选择
      performanceReference: 0, //卡项消耗业绩计算基准
      performanceValue: undefined, // 卡项消耗业绩计算方式-值
      performanceUnit: 0, //卡项消耗业绩计算方式-右侧选择，0 元/日， 1 %/月
      isPerformance: false, //是否计算消耗业绩
      commission: undefined, //消耗提成
      commissionUnit: 0, //消耗提成单位
      refundDeadline: 0, //退款时限
      isAfterSale: false, //支持售后
      skuId: generateNumericUUID(), //前端自定义生成的skuId
      spuData: {
        skus: []
      }
    }
  ]
  // 重置商品权限
  Object.assign(formData, fromDataRule)
  Object.assign(props.propFormData, formData)
}

/** 调用 SkuList generateTableData 方法*/
const generateSkus = (propertyList: any[]) => {
  skuListRef.value.generateTableData(propertyList)
  Object.assign(props.propFormData, formData)
}
</script>
